package com.dwusoft.license;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

/**

 * 生成license文件

 */
public class Anquan {

	public static void main(String arg[]) throws Exception {
		//生成密钥

		String msg = "";
		String pathss = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		pathss = pathss.substring(1);

		FileInputStream fis = new FileInputStream(pathss + "/com/dwusoft/license/msg.xml");
		byte[] b = new byte[fis.available()];
		fis.read(b);
		fis.close();
		msg = new String(b, "UTF-8");
		String path = pathss + "/98/";
		String realpath = pathss + "/98/";
		FileOperate.getInstance().newCreateFolder(path);
		FileOperate.getInstance().newCreateFolder(realpath);
		Anquan anquan = new Anquan();
		anquan.createKey(realpath, "dwusoft");
		anquan.getDSAStr(msg, realpath, "dwusoft", path);
		System.out.println("文件已生成,请在此工程的bin/98目录下取,dwusoft.dll,dwusoft_public.dll两个文件发给项目组");
	}

	/**

	 * <P>生成密钥文件</P>

	 * @param path 生成的密钥文件的存放位置

	 * @throws Exception

	 */
	public void createKey(String path, String key) throws Exception {
		KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
		keygen.initialize(512);
		KeyPair kp = keygen.generateKeyPair();
		PublicKey publickey = kp.getPublic();
		PrivateKey privatekey = kp.getPrivate();
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path + key + "_public.dll"));
		out.writeObject(publickey);
		out.close();
		ObjectOutputStream out_private = new ObjectOutputStream(new FileOutputStream(path + key + "_no_use.bat"));
		out_private.writeObject(privatekey);
		out_private.close();
	}

	/**

	 * <P>用私钥将信息加密</P>

	 * @param msg 要加密的信息

	 * @param dsapath 已经生成的密钥位置

	 * @param key 要发放密钥的单位 

	 * @param address 生成加密文件的地址

	 * @return

	 * @throws Exception

	 */
	public void getDSAStr(String msg, String dsapath, String key, String address) throws Exception {
		msg = TeaUtil.encryptByTea(msg);
		ObjectInputStream privatein = new ObjectInputStream(new FileInputStream(dsapath + key + "_no_use.bat"));
		PrivateKey privatekey = (PrivateKey) privatein.readObject();
		privatein.close();
		Signature sign = Signature.getInstance("DSA");
		sign.initSign(privatekey);
		sign.update(msg.getBytes());
		byte[] update = sign.sign();
		ObjectOutputStream objout = new ObjectOutputStream(new FileOutputStream(address + key + ".dll"));
		objout.writeObject(msg);
		objout.writeObject(update);
		objout.close();
		return;
	}

}